package cn.tomoki.myapplication;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.se.omapi.Session;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import cn.tomoki.config.UserId;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import javax.security.auth.Subject;

import cn.tomoki.adapters.ListViewAdapter;
import cn.tomoki.beans.ItemBean;
import cn.tomoki.beans.User;
import cn.tomoki.login.CodeUtils;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private String[] list = {"请选择角色","入库人员","领用人","维修人员","高级管理员"};
    private TextView myTextView;
    private Spinner mySpinner;
    private ArrayAdapter<String> adapter;
    private ImageView img_yzm;
    private EditText ed_uname, ed_pwd, ed_yzm;
    private CodeUtils codeUtils;
    private Button btn_login, btn_cz;
    private String codeStr, uname, upwd,role = "";   //登录需要的基本信息
    private boolean state;  //登录状态
    private String msg; //登录信息
    public static User app = null;    //登录用户
    public static String appUser;
    private static String session;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FormBody.Builder params = new FormBody.Builder();
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(Utils.classroomUrl+"/user/session")
                            .post(params.build())
                            .build();//创造http请求
                    Response response = client.newCall(request).execute();
                    String result = response.body().string();
                    JSONObject jsonObject = new JSONObject(result);
                    session = jsonObject.getString("session");
//                    System.out.println("session为："+session);
                    if(!session.equals("")){
                        UserId.UserId = session;
                        Intent intent = new Intent();
                        intent.setClass(MainActivity.this,OutUserActivity.class);
                        finish();
                        startActivity(intent);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "欢迎回来"+session, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "你的账户已过期，请重新登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();

        initView();
        initData();
        mySpinner = (Spinner)findViewById(R.id.Spinner);
        ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,R.layout.myspinner,list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mySpinner.setAdapter(adapter);
        mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
                role = list[arg2];  //获取选中的角色值
                arg0.setVisibility(View.VISIBLE);
            }
            public void onNothingSelected(AdapterView<?> arg0){
                arg0.setVisibility(View.VISIBLE);
            }
        });
        mySpinner.setOnTouchListener(new Spinner.OnTouchListener(){
            public  boolean onTouch(View v, MotionEvent event){
                return false;
            }
        });
        mySpinner.setOnFocusChangeListener(new Spinner.OnFocusChangeListener(){
            public void onFocusChange(View v,boolean hasFocus){

            }
        });
        System.out.println("session:"+session+appUser);
}
    private void initView() {
        img_yzm = (ImageView) findViewById(R.id.img_yzm);
        ed_uname = (EditText) findViewById(R.id.ed_uname);
        ed_pwd = (EditText) findViewById(R.id.ed_pwd);
        ed_yzm = (EditText) findViewById(R.id.ed_yzm);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_cz = (Button) findViewById(R.id.btn_cz);
    }

    private void login(User user){
        //接受后端数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                   String json = "{\n" +
                           "    \"role\":\""+user.getRole()+"\",\n" +
                           "    \"username\":\""+user.getUsername()+"\",\n" +
                           "    \"password\":\""+user.getPassword()+"\"\n" +
                           "}";
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(Utils.classroomUrl+"/user/login")
                            .post(RequestBody.create(MediaType.parse("application/json"),json))
                            .build();//创造http请求
                    Response response = client.newCall(request).execute();
                    String result = response.body().string();
                    JSONObject jsonObject = new JSONObject(result);
                    System.out.println(jsonObject);
                     msg = jsonObject.getString("msg"); //获取登录信息
                    state = jsonObject.getBoolean("state"); //获取登录状态
                    appUser = jsonObject.getString("user");
                    if (state) {
                        System.out.println("state为true");
                        UserId.UserId = appUser;
                        Intent intent = new Intent();
                        intent.putExtra("uname", uname);
                        if(role.equals("领用人")){
                            intent.setClass(MainActivity.this,OutUserActivity.class);
                        }
                        finish();
                        startActivity(intent);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();

                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();

                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }


    private void initData() {
//      设置验证码，验证码项目需要SDK降级
        codeUtils = CodeUtils.getInstance();
        Bitmap bitmap = codeUtils.createBitmap();
        img_yzm.setImageBitmap(bitmap);
        img_yzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                codeUtils = CodeUtils.getInstance();
                Bitmap bitmap = codeUtils.createBitmap();
                img_yzm.setImageBitmap(bitmap);
                String code = codeUtils.getCode().toLowerCase();
                System.out.println("code------------:" + code);
            }
        });


//        设置登录按钮
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                将获取的验证码进行小写判断
                codeStr = ed_yzm.getText().toString().trim().toLowerCase();
                uname = ed_uname.getText().toString().trim();
                upwd = ed_pwd.getText().toString().trim();
                String code = codeUtils.getCode().toLowerCase();
                app = new User(role,uname,upwd);

//                进行验证码判断
                if (null == codeStr || TextUtils.isEmpty(codeStr)||!code.equalsIgnoreCase(codeStr)) {
                    Toast.makeText(MainActivity.this, "请输入正确验证码", Toast.LENGTH_SHORT).show();
                }
//                将验证码变成小写字母

                System.out.println("code------------:" + code);
                if (code.equalsIgnoreCase(codeStr)) {
                    login(app);
                }
            }
        });
        btn_cz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ed_pwd.setText("");
                ed_uname.setText("");
                ed_yzm.setText("");
            }
        });


    }}